package com.heima.wemedia.service.impl;

import com.heima.common.dtos.AppHttpCodeEnum;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.exception.LeadNewsException;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemedia.dtos.WmLoginDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.BCrypt;
import com.heima.utils.common.JwtUtils;
import com.heima.utils.common.RsaUtils;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.Map;

@Service
public class WmUserServiceImpl implements WmUserService {

    @Value("${leadnews.jwt.privateKeyPath}")
    private String privateKeyPath; // 私钥路径

    @Value("${leadnews.jwt.expire}")
    private Integer expire; // 过期时间

    @Autowired
    private WmUserMapper wmUserMapper;

    @Override
    public ResponseResult login(WmLoginDto dto) {

        if (StringUtils.isEmpty(dto.getName())|| StringUtils.isEmpty(dto.getPassword())){
            throw new LeadNewsException(AppHttpCodeEnum.PARAM_INVALID);
        }


            // 用户登录
            // 查询用户是否存在
            WmUser loginUser = wmUserMapper.findByDto(dto);
            System.err.println("loginUser = " + loginUser);

            if (loginUser == null){
//                throw new RuntimeException("用户不存在");
//                throw new LeadNewsException(404,"用户不存在");
                throw new LeadNewsException(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
            // 判断密码是否正确
            if (!BCrypt.checkpw(dto.getPassword(),loginUser.getPassword())){
//                throw new RuntimeException("密码错误");
//                throw new LeadNewsException(500,"密码错误");
                throw new LeadNewsException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }

            try {
                // 获取私钥文件
                PrivateKey privateKey = RsaUtils.getPrivateKey(privateKeyPath);

                // 生成token
                // 去掉敏感数据
                loginUser.setPassword(null);
                String token = JwtUtils.generateTokenExpireInMinutes(loginUser, privateKey, expire);

                Map<String,Object> map = new HashMap<>();
                map.put("token",token);
                map.put("user",loginUser);

                // 返回信息给前端
                return ResponseResult.okResult(map);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("加载私钥失败");
            }

    }
}
